package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.constant.MongoDbConstant;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.PressureHis;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.SimpleMongoService;
import com.bbzn.device.client.utils.OptionalBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Component
public class EmqBloodPreStrategy implements EmqStrategy {

    @Autowired
    private SimpleMongoService simpleMongoService;

    @Autowired
    private DeviceService deviceService;

    // 手表血压信息
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            Integer systolic = jsonObject.getInteger("systolic");
            if (!OptionalBean.ofNullable(systolic).isPresent()) {
                return "json解析错误";
            }
            Integer diastolic = jsonObject.getInteger("diastolic");
            if (!OptionalBean.ofNullable(systolic).isPresent()) {
                return "json解析错误";
            }
            PressureHis pressureHis = new PressureHis();
            pressureHis.setImei(imei);
            pressureHis.setSystolic(systolic);
            pressureHis.setDiastolic(diastolic);
            pressureHis.setCreateTime(System.currentTimeMillis());
            pressureHis.setCreatedBy("emq");
            simpleMongoService.insert(pressureHis, MongoDbConstant.PRESSURE_HIS);


            Device device = new Device();
            device.setImei(imei);
            device.setSystolic(systolic);
            device.setDiastolic(diastolic);
            deviceService.updateByImeiSelective(device);
        } catch (Exception e) {
            return "获取血压失败！";
        }
        return "获取血压成功！";
    }
}
